<template>
	<view>
		<view class="navbar">
			<view class="status-bar"></view>
			<view class="navbar-inner" :style="[navbarInnerStyle]">
				<view class="back-wrap" v-if="isBack" :style="fontStyle" @touchend="goBack">
					<view class="">
						<text class="iconfont icon-fanhui"></text>
					</view>
					<view v-if="backText" class="" :style="fontStyle">{{ backText }}</view>
				</view>
				<view class="navbar-content-title" v-if="title" :style="[titleStyle,fontStyle]">{{title}}</view>
				<slot name="right"></slot>
			</view>
		</view>
	</view>
</template>

<script>
	// 获取系统状态栏的高度
	let systemInfo = uni.getSystemInfoSync()
	export default {
		props: {
			// 返回按钮右边的提示文字
			backText: {
				type: String,
				default: ''
			},
			// 导航栏标题
			title: {
				type: String,
				default: ''
			},
			// 标题的颜色
			titleColor: {
				type: String,
				default: '#606266'
			},
			// 背景色
			bgColor: {
				type: String,
				default: '#ffffff'
			},
			// 标题字体是否加粗
			titleBold: {
				type: Boolean,
				default: false
			},
			// 标题的字体大小
			titleSize: {
				type: [String, Number],
				default: 32
			},
			isBack: {
				type: [Boolean, String],
				default: true
			},
			isCusBack: {
				type: [Boolean, String],
				default: false
			},
		},
		data() {
			return {
				fontStyle: {
					color: this.titleColor,
					fontSize: this.titleSize + 'rpx',
					fontWeight: this.titleBold ? 'bold' : 'normal'
				},
				// 导航中间的标题的样式
				titleStyle: {
					paddingRight: 0
				}
			}
		},
		computed: {
			// 导航栏内部盒子的样式
			navbarInnerStyle() {
				let style = {};
				// 导航栏宽度，如果在小程序下，导航栏宽度为胶囊的左边到屏幕左边的距离
				style.height = this.navbarHeight + 'px'
				style.backgroundColor = this.bgColor
				return style
			},
			// 转换字符数值为真正的数值
			navbarHeight() {
				return this.height ? this.height : 44
			},
		},
		created() {
			this.init()
		},
		methods: {
			init() {
				const _this = this
				this.$nextTick(function() {
					let query = uni.createSelectorQuery().in(_this)
					query.select('.navbar-content-title').boundingClientRect(data => {
						let t_width = data === null ? 0 : data.width
						_this.titleStyle.paddingRight = ((systemInfo.windowWidth - t_width) / 2) + 'px'
					}).exec()
				})
			},
			goBack() {
				if (this.isCusBack) {
					this.$emit('back')
				} else {
					uni.navigateBack()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.navbar {}

	.status-bar {
		width: 100%;
		height: var(--status-bar-height);
	}

	.navbar-inner {
		position: relative;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-right: 24rpx;
	}

	.navbar-content-title {
		// position: absolute;
		white-space: nowrap;
		// margin: auto;
	}

	.back-wrap {
		display: flex;
		align-items: center;
		flex: 1;
		flex-grow: 0;
		padding: 14rpx 14rpx 14rpx 24rpx;
	}
</style>
